package com.example.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.example.easyexcel.Service.UserService;
import com.example.easyexcel.Service.impl.UserServiceImpl;
import com.example.easyexcel.entity.DemoData;
import com.example.easyexcel.listener.UploadListener;
import com.example.easyexcel.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 测试Controller
 *
 * @VERSION V1.0
 * @DESCRIPTION com.paic.luchang.center.aggregation.controller
 * @AUTH luchang
 * @DATE 2019/9/7
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileManageController {

    /**
     * 文件下载，excel表格形式
     *
     * @param response
     * @throws FileNotFoundException
     */
    @RequestMapping(value = "/fileDownload", method = RequestMethod.GET)
    public void download(HttpServletResponse response) throws FileNotFoundException {
        String fileName="下载测试.xlsx";
        FileUtil.downloadExcel(response,fileName);
    }

    /**
     * 文件下载，数据形式
     *
     * @param response
     * @throws FileNotFoundException
     */
    @RequestMapping(value = "/dataFileDownload", method = RequestMethod.GET)
    public void datafileDownload(HttpServletResponse response) throws FileNotFoundException {
        try {
            FileUtil.downloadExcel(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * excel上传
     *
     * @param file          文件
     * @param headRowNumber 标题所在行行号
     * @throws IOException
     */
    @PostMapping("/upLoad")
    public String uploadExcel(MultipartFile file, Integer headRowNumber) throws IOException {
        // headRowNumber为标题所在行号
        EasyExcel.read(file.getInputStream(), DemoData.class, new UploadListener(new UserServiceImpl())).headRowNumber(headRowNumber).sheet().doRead();
        return "success";
    }

}
